
function io(io) {

  io.on('connection', function (socket) {
    //用户只允许发消息
    //加入房间
    //给房间所有的人发信息
    socket.on("online", (str) => {
        let roomType = str.roomType
        if(roomType==='single'){
          socket.join(str.username);
          io.to(str.username).emit("message", {
            "message": str.realname + "加入房间",
            "type": "notice"
        })
        }else if(roomType==='many'){
          socket.join('publicRoom');
        }
      // }
    })
    socket.on("in",(str)=>{
      socket.join(str.username);

    })
    socket.on("send",function(str){
      console.log("str");
    })
    socket.on("remark",(msg)=>{
      console.log(msg);
      io.to(msg.username).emit("remarkMessge",msg)
    })
    //当收到消息后给所有人发信息
    socket.on('message', function (str) {
      let roomType = str.roomType
      if(roomType==='single'){
        io.to(str.username).emit("message", {
          "message": str.msg,
          "username": str.username,
          "type": "chat",
          "realname": str.realname,
          "UserId": str.id,
          "avatar": str.avatar
        });
        io.to("2628735401").emit("message", {
          "message": str.msg,
          "username": str.username,
          "type": "chat",
          "realname": str.realname,
          "roomId": str.username,
          "avatar": str.avatar
        });
      }else if(roomType==='many'){
        io.to('publicRoom').emit('message',{
          "content": str.msg,
          "username":str.username,
          "type": "chat",
          "realname": str.realname,
          "UserId": str.id,
          "avatar": str.avatar
        })
      }
      
    })

    // 当收到指令后加入到指定房间 room为房间号 前端传过来的
    socket.on('join', (room) => {
      
      socket.join(room.username);
      // socket.on('message',function (str) {  
      io.to(room.username).emit("message", {
        "message": room.realname + "加入房间",
        "type": "notice"
      });
      // })  
    })

    socket.on("leave",(room) =>{
      let roomType = room.roomType
      if(roomType==='single'){
        io.to(room.username).emit("message",{
          "message":room.realname + "离开房间",
          "type": "notice"
        })
      socket.leave(room.username)

      }else if(roomType === 'many'){
      socket.leave('publicRoom')

      }

    })


    // 客户端断开，自带事件
    socket.on('disconnect', function () {
      io.emit('message', {
        "message": "断开连接",
        "type": "notice"
      })
    })
  })
}

module.exports = io